Symbolic operation with sympy


In [1]:
import sympy

sympy.init_printing(use_latex='mathjax')

In [2]:
# define symbol
x = sympy.symbols('x')
print(type(x))
x


<class 'sympy.core.symbol.Symbol'>
Out[2]:
$$x$$

In [3]:
# define fuction
f = x**2 + 4*x
f


Out[3]:
$$x^{2} + 4 x$$

In [4]:
# differentiation
sympy.diff(f)


Out[4]:
$$2 x + 4$$

In [5]:
# simplify function
sympy.simplify(f)


Out[5]:
$$x \left(x + 4\right)$$

In [6]:
# solving equation
from sympy import solve

solve(f)


Out[6]:
$$\left [ -4, \quad 0\right ]$$

In [7]:
# factorize
from sympy import factor
sympy.factor(f)


Out[7]:
$$x \left(x + 4\right)$$

In [8]:
# partial differentiation
x, y = sympy.symbols('x y')
f = x**2 + 4*x*y + y**2
f


Out[8]:
$$x^{2} + 4 x y + y^{2}$$

In [9]:
# sympy.diff(a, b)
## a: function, b: variable
sympy.diff(f, x)


Out[9]:
$$2 x + 4 y$$

In [10]:
sympy.diff(f, y)


Out[10]:
$$4 x + 2 y$$

Draw function graph


In [11]:
# draw 2nd degree function
def f2(x):
    return x**3 + 2*x**2 - 20

x = np.linspace(-21, 21, 500)
y = f2(x)

plt.plot(x, y)
plt.show()


Gradient vector, quiver & contour plot


In [12]:
import numpy as np
import matplotlib as mpl
import matplotlib.pylab as plt

In [13]:
# function definition
def f(x, y):
    return 3*x**2 + 4*x*y + 4*y**2 - 50*x - 20*y + 100

# coordinate range
xx = np.linspace(-11, 16, 500)
yy = np.linspace(-11, 16, 500)

# make coordinate point
X, Y = np.meshgrid(xx, yy)

# dependent variable point on coordinate
Z = f(X, Y)

from mpl_toolkits.mplot3d import Axes3D

# draw surface plot
fig = plt.figure(figsize=(15, 10))
fig.gca(projection='3d').plot_surface(X, Y, Z)
plt.xlabel('x')
plt.ylabel('y')
plt.show()



In [14]:
# gradient vector(x)
def gx(x, y):
    return 6*x + 4*y - 50

# gradient vector(y)
def gy(x, y):
    return 8*y + 4*x - 20

# gradient vector point and coordinate
xx2 = np.linspace(-10, 15, 10)
yy2 = np.linspace(-10, 15, 10)
X2, Y2 = np.meshgrid(xx2, yy2)

GX = gx(X2, Y2)
GY = gy(X2, Y2)

# gradient vector quiver plot
plt.figure(figsize=(10, 10))

## make contour plot
contour = plt.contour(X, Y, Z, cmap='pink', levels=[-100, 0, 100, 200, 400, 800, 1600])
## contour plot labeling
plt.clabel(contour, inline=1, fontsize=10)
## make quiver plot
## plt.quiver(x, y, gx, gy): draw vector from (x, y) to (gx, gy)
plt.quiver(X2, Y2, GX, GY, color='pink', width=0.003, scale=600)
## plot labeling
plt.axis('equal')
plt.xlabel('x')
plt.ylabel('y')
plt.show()